import { confirmOrderApi } from '@/api/order'
import useCartEffect from '@/hooks/useCartEffect'
import { defineComponent, ref } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import Modal from '@/components/Modal'

/* 提交订单 */
const useMakeOrderEffect = (toggleSuccessShow: (isShow: boolean) => void) => {
  const router = useRouter()
  const route = useRoute()
  const shopId = route.params.shopId as string
  const { cartInfo, purchaseCartArray, clearShopCart } = useCartEffect(shopId)

  const handleSuccessClose = () => {
    router.push({ name: 'OrderList' })
    clearShopCart()
  }

  const handleConfirmClcik = async (isCanceled: boolean) => {
    const res = await confirmOrderApi({
      addressId: '1',
      shopId,
      shopName: cartInfo.value.shopName,
      isCanceled,
      products: purchaseCartArray.value.map(product => ({ id: product.id, count: product.count }))
    })
    if (res.code === 0) {
      toggleSuccessShow(true)
    }
  }

  return {
    cartInfo,
    handleConfirmClcik,
    handleSuccessClose
  }
}

/* 显隐弹窗 */
const useShowMaskEffect = () => {
  // 确认订单弹窗
  const showConfirm = ref(false)
  const toggleConfirmShow = (isShow: boolean) => {
    showConfirm.value = isShow
  }
  // 支付成功弹窗
  const showSuccess = ref(false)
  const toggleSuccessShow = (isShow: boolean) => {
    showSuccess.value = isShow
  }

  return {
    showConfirm,
    toggleConfirmShow,
    showSuccess,
    toggleSuccessShow
  }
}

export default defineComponent({
  name: 'Order',
  setup () {
    const { showConfirm, toggleConfirmShow, showSuccess, toggleSuccessShow } = useShowMaskEffect()
    const { cartInfo, handleConfirmClcik, handleSuccessClose } = useMakeOrderEffect(toggleSuccessShow)
    /* render 函数 */
    return () => {
      return (
        <>
          <div class="order">
            <div class="order__price">实付金额<b>￥{ cartInfo.value.price.toFixed(2) }</b></div>
            <div class="order__btn" onClick={ () => { toggleConfirmShow(true) } }>提交订单</div>
          </div>
          <Modal class="confirm" v-model={ [showConfirm.value, 'visible'] } >
            <h3 class="confirm__title">确认要离开收银台？</h3>
            <p class="confirm__desc">请尽快完成支付，否则将被取消</p>
            <div class="confirm__btns">
              <div class="confirm__btn cancel" onClick ={ () => handleConfirmClcik(true) }>取消订单</div>
              <div class="confirm__btn confirm" onClick={ () => handleConfirmClcik(false) }>确认支付</div>
            </div>
          </Modal>
          <Modal
            class="success"
            v-model={ [showSuccess.value, 'visible'] }
            showClose
            onClose={ handleSuccessClose }>
            <i class="iconfont icon-check"></i>
            <div class="success__content">支付成功，等待配送</div>
          </Modal>
        </>
      )
    }
  }
})
